<?php
/**
 * 百度链接提交
 * User: Administrator
 * Date: 2017/6/4
 * Time: 17:46
 */

namespace app\admin\model;

use think\Model;

class Baidu extends Model
{

    const API_TYPE_INSERT = 1; //推送
    const API_TYPE_UPDATE = 2; //更新
    const API_TYPE_DEL = 3;  //删除接口
    const SEND_STATUS_SUCCESS = 1; //推送成功
    const SEND_STATUS_ERROR = 0; //推送失败


    /**
     * 百度推送接口类型
     * @return array
     */
    public function getApiType($apiType)
    {
        $data = ['1'=>'推送','2'=>'更新','3'=>'删除'];
        return $data[$apiType];
    }

    /**
     * 发送状态
     * @param $sendStatus
     * @return mixed
     */
    public function getSendStatus($sendStatus)
    {
        $data = ['1'=>'成功','0'=>'失败'];
        return $data[$sendStatus];
    }


    /**
     *推送数据
     */
    public function sendUrl($urls)
    {
        $api = 'http://data.zz.baidu.com/urls?site=tp5.yeafy.com&token=5vnstaaS4v5NuNp8';
//        $urls = 'http://tp5.yeafy.com/home/cases/index/cid/5.html';
        $_result = $this->baiduCurl($api,$urls);
        //日志记录
        $this->baiduLog($urls, $_result, self::API_TYPE_INSERT);
    }

    /**
     * 百度主动推送
     * @param $api  //百度接口
     * @param $urls  //收录地址
     * @return mixed
     */
    public function baiduCurl($api,$urls)
    {
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => $urls,
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }


    /**
     * 推送日志记录
     * @param $urls
     * @param $_result
     * @param $api_type
     */
    public function baiduLog($urls,$_result,$api_type)
    {
        $data['url'] = $urls;
        $data['result'] = $_result;
        $data['add_time'] = time();
        $data['api_type'] = $api_type;
        $result = json_decode($_result,true);
        if(isset($result['success']))
        {
            $data['send_status'] = self::SEND_STATUS_SUCCESS;
            db('baidu')->insert($data);
        }
        else
        {
            $data['send_status'] = self::SEND_STATUS_ERROR;
            db('baidu')->insert($data);
        }
    }




}